package com.imut.lagain.config;

import com.imut.lagain.filter.JwtAuthenticationFilter;
import com.imut.lagain.filter.JwtAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Arrays;

/**
 * Spring Security配置类
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig {
    
    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter;
    
    private static final Logger log = LoggerFactory.getLogger(SecurityConfig.class);
    
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        log.info("=== 配置SecurityFilterChain ===");
        
        http
            .csrf(csrf -> {
                log.info("禁用CSRF保护");
                csrf.disable();
            })
            .cors(cors -> {
                log.info("配置CORS");
                cors.configurationSource(corsConfigurationSource());
            })
            .sessionManagement(session -> {
                log.info("配置Session管理为无状态");
                session.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
            })
            .authorizeHttpRequests(auth -> {
                log.info("配置请求授权规则");
                auth
                    .requestMatchers("/auth/**").permitAll()
                    .requestMatchers("/phone-auth/**").permitAll()
                    .requestMatchers("/test/**").permitAll()
                    .requestMatchers("/test-auth/**").permitAll()
                    .requestMatchers("/public/**").permitAll()
                    // 文件上传接口需要认证
                    .requestMatchers("/files/upload/image").authenticated()
                    .requestMatchers("/files/upload/audio").authenticated()
                    // 用户信息和胶囊接口需要认证
                    .requestMatchers("/user/info").authenticated()
                    .requestMatchers("/capsules/**").authenticated()
                    // 文件访问端点允许匿名访问（因为是公开资源）
                    .requestMatchers("/files/images/**").permitAll()
                    .requestMatchers("/files/audios/**").permitAll()
                    .requestMatchers("/files/voices/**").permitAll()
                    // 添加更通用的文件访问规则
                    .requestMatchers("/files/**").permitAll()
                    // 根路径允许访问
                    .requestMatchers("/").permitAll()
                    .requestMatchers("/api").permitAll()
                    // 所有其他API接口需要认证
                    .requestMatchers("/api/**").authenticated()
                    // Actuator和Swagger允许匿名访问
                    .requestMatchers("/actuator/**").permitAll()
                    .requestMatchers("/swagger-ui/**").permitAll()
                    .requestMatchers("/v3/api-docs/**").permitAll()
                    // 更安全的默认配置
                    .anyRequest().authenticated();
                log.info("请求授权规则配置完成");
            });
        
        // 添加JWT认证过滤器
        log.info("添加JWT认证过滤器");
        http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
        
        log.info("SecurityFilterChain配置完成");
        return http.build();
    }
    
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        log.info("配置CORS源");
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOriginPatterns(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        configuration.setAllowedHeaders(Arrays.asList("Content-Type", "Authorization", "X-Requested-With"));
        configuration.setAllowCredentials(true);
        
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}